package com.hnichr.ump.assessment.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.lang.Validator;
import com.beisen.sdk.Constants;
import com.beisen.sdk.assessment.model.*;
import com.beisen.sdk.assessment.model.Dimension;
import com.beisen.sdk.assessment.model.TestReport;
import com.beisen.sdk.assessment.model.TesteeResult;
import com.hnichr.ump.common.assessment.entity.*;
import com.hnichr.ump.common.assessment.entity.Template;
import com.hnichr.ump.common.assessment.service.*;
import com.hnichr.ump.common.assessment.vo.*;
import com.hnichr.ump.common.schedule.dto.RunResultDTO;
import com.mxpioframework.jpa.JpaUtil;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AssessmentServiceImpl implements AssessmentService {

    private static final Logger logger = LoggerFactory.getLogger(AssessmentServiceImpl.class);

    @Autowired
    private AssessmentInterfService interfService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private InviteService inviteService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private PaperService paperService;

    @Autowired
    private OptionService optionService;

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.resUrl}")
    private String resUrl;
    /**
     * 获取活动列表
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<ActivityVO> listVO() {
        List<Activity> activityList = JpaUtil.linq(Activity.class).equal("state","1").equal("displayState","1").desc("orderNum","activityCreateDate").list();
        return assembleActivityVO(activityList);
    }

    @Override
    @Transactional(readOnly = true)
    public List<ActivityVO> listVO(String tenantId) {
        List<Activity> activityList = JpaUtil.linq(Activity.class).equal("state","1").equal("displayState","1").equal("tenantId",tenantId).desc("orderNum","activityCreateDate").list();
        return assembleActivityVO(activityList);
    }


    @Override
    @Transactional
    public void submitAnswer(SubmitAnswerVO vo){
        if(CollectionUtils.isEmpty(vo.getQuestionAnswerList())){
            return;
        }
        Invite invite = inviteService.getById(Invite.class,vo.getInviteId());
        for(QuestionAnswerVO questionAnswer:vo.getQuestionAnswerList()){
            if(CollectionUtils.isEmpty(questionAnswer.getOptionAnswerList())){
                continue;
            }
            Question question = questionService.getById(Question.class,questionAnswer.getQuestionId());
            for(OptionAnswerVO optionAnswerVO:questionAnswer.getOptionAnswerList()){
                Answer answer = new Answer();
                answer.setId(UUID.fastUUID().toString());
                answer.setTenantId(invite.getTenantId());
                answer.setInviteId(vo.getInviteId());
                answer.setTesteeId(invite.getTesteeId());
                answer.setPaperId(vo.getPaperId());
                answer.setQuestionId(questionAnswer.getQuestionId());
                answer.setQuestionType(question.getQuestionType());
                answer.setQuestionOrderNum(question.getOrderNum());
                //简答题
                if(StringUtils.equals(question.getQuestionType(),Question.TYPE.ANSWER.getCode())){
                    AnswerText answerText = new AnswerText();
                    answerText.setAnswerId(answer.getId());
                    answerText.setAnswerText(optionAnswerVO.getOptionText());
                    JpaUtil.save(answerText);
                    answer.setAnswerdTextId(answerText.getId());
                    answer.setOptionOrderNum(99);
                }
                else {
                    answer.setAnswerdOptionId(optionAnswerVO.getOptionId());
                    Option option = optionService.getById(Option.class,optionAnswerVO.getOptionId());
                    answer.setOptionOrderNum(option.getOrderNum());
                }
                JpaUtil.save(answer);
            }
        }
    }

    /**
     * 用户注册
     * @param vo
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public TesteeRegisterResultVO register(TesteeRegisterVO vo){
        //数据合法性校验

        TesteeRegisterResultVO validResult =  registerInputValid(vo);
        if(validResult!=null){
            return validResult;
        }

        //邮箱统一使用小写
        vo.setEmail(StringUtils.lowerCase(vo.getEmail()));

        //北森状态
        Activity activity = JpaUtil.linq(Activity.class).equal("id",vo.getActivityId()).findOne();
        if(!StringUtils.equals(activity.getState(),"1")){
            logger.error("活动不可用,id:{},state:{}",activity.getId(),activity.getState());
            return TesteeRegisterResultVO.error("活动已"+(StringUtils.equals(activity.getState(),"2")?"停用":"删除"));
        }

        //本地维护显示状态
        if(!StringUtils.equals(activity.getDisplayState(),"1")){
            logger.error("活动已隐藏,id:{}",activity.getId());
            return TesteeRegisterResultVO.error("活动已停用");
        }

        //获取邮件模板id
        List<Template> templateList = JpaUtil.linq(Template.class).equal("templateType","0").equal("channel","0").list();
        if(CollectionUtils.isEmpty(templateList)){
            logger.error("无法获取邮件模板");
            return TesteeRegisterResultVO.error("无法获取邮件模板");
        }

        boolean isNewTestee = true;
        Testee testee = null;
        List<Testee> existsTestees = JpaUtil.linq(Testee.class).equal("email",vo.getEmail()).equal("tenantId",activity.getTenantId()).list();
        //已注册，更新
        if(CollectionUtils.isNotEmpty(existsTestees)){
            isNewTestee = false;
            testee = existsTestees.get(0);
            testee.setName(vo.getName());
            testee.setGender(vo.getGender());
            testee.setBirthday(vo.getBirthday());
            testee.setGraduationDate(vo.getGraduationDate());
            testee.setGraduationSchool(vo.getGraduationSchool());
            testee.setMajor(vo.getMajor());
            testee.setMobile(vo.getMobile());
            JpaUtil.update(testee);
        }
        //未注册，新增
        else{
            testee = new Testee();
            BeanUtils.copyProperties(vo,testee);
            testee.setTenantId(activity.getTenantId());
            JpaUtil.save(testee);
        }
        String testeeId = testee.getId();

        //如果不是新注册用户，需要判断是否已经发起邀请
        if(!isNewTestee){
            List<Invite> existsInviteList = JpaUtil.linq(Invite.class).equal("testeeId",testeeId).equal("activityId",vo.getActivityId()).equal("inviteResult","1").list();
            if(CollectionUtils.isNotEmpty(existsInviteList)){
                for(Invite existsInvite:existsInviteList){
                    if(StringUtils.isNotBlank(existsInvite.getTestUrl())){
                        //完成作答,肯定已经做过本地的题目，直接跳转北森url
                        if(StringUtils.equals(existsInvite.getState(),Invite.STATE.ASSESSMENT_COMPLATED.getCode())){
                            return TesteeRegisterResultVO.redirectBeisenUrl(existsInvite.getTestUrl());
                        }
                        //未开始或者作答中
                        else{
                            //此处需要有效时间
                            Date now = new Date();
                            if(now.after(existsInvite.getStartTime())&&now.before(existsInvite.getEndTime())){
                                //如果作答中，肯定已经做过本地的题目，直接跳转北森url
                                if(StringUtils.equals(existsInvite.getState(),Invite.STATE.ASSESSMENT_PROCESSING.getCode())){
                                    return TesteeRegisterResultVO.redirectBeisenUrl(existsInvite.getTestUrl());
                                }
                                //未作答
                                else{
                                    //没有设置本地题目
                                    if(StringUtils.isBlank(activity.getPaperId())){
                                        return TesteeRegisterResultVO.redirectBeisenUrl(existsInvite.getTestUrl());
                                    }
                                    else{
                                        //判断此次邀请是否已答本地题目
                                        Long answercount = JpaUtil.linq(Answer.class).equal("inviteId",existsInvite.getId()).count();
                                        //做过，直接跳转北森url
                                        if(answercount>0){
                                            return TesteeRegisterResultVO.redirectBeisenUrl(existsInvite.getTestUrl());
                                        }
                                        //未答本地题目，需要跳转本地题目
                                        else{
                                            PaperVO paper = getPaper(activity.getPaperId());
                                            if(paper==null){
                                                return TesteeRegisterResultVO.redirectBeisenUrl(existsInvite.getTestUrl());
                                            }
                                            else{
                                                return TesteeRegisterResultVO.redirectLocalPaper(paper,existsInvite.getId(),existsInvite.getTestUrl());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
        Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
        Date endDay = DateUtils.addDays(today, Constants.EFFECTIVE_TIME);


        TesteeInfoParameterList parameterList = new TesteeInfoParameterList();
        TesteeInfoParameter parameter = new TesteeInfoParameter();
        parameter.email = vo.getEmail();
        parameter.name = vo.getName();
        parameter.mobile = vo.getMobile();
        parameter.moreinfo = new TesteeInfo();
        parameter.moreinfo.birthday = vo.getBirthday();
        if(StringUtils.equals(vo.getGender(),"M")){
            parameter.moreinfo.sex = "男";
        }
        else if(StringUtils.equals(vo.getGender(),"F")){
            parameter.moreinfo.sex = "女";
        }


        parameterList.add(parameter);

        Invite invite = new Invite();
        invite.setActivityId(vo.getActivityId());
        invite.setActivityName(activity.getName());
        invite.setEmail(vo.getEmail());
        invite.setTesteeId(testeeId);
        invite.setStartTime(today);
        invite.setEndTime(endDay);
        invite.setState(Invite.STATE.NOT_STARTED.getCode());
        invite.setResultState(Invite.RESULT_STATE.NOT_SYNC.getCode());
        invite.setTenantId(activity.getTenantId());
        JpaUtil.save(invite);

        TesteeResult testeeResult = null;
        try{
            testeeResult = interfService.sendEmailInviteTestee(Integer.parseInt(activity.getBsActivityId()),formatter.format(today),formatter.format(endDay),templateList.get(0).getId(),parameterList);
        }
        catch (Exception e){
            logger.error("测评邀请接口调用失败:{}",e.getMessage(),e);
        }
        if(testeeResult==null){
            invite.setInviteResult(Invite.INVITE_RESULT.INTERFACE_ERROR.getCode());
        }
        else{
            if(CollectionUtils.isNotEmpty(testeeResult.error_testee_list)){
                invite.setInviteResult(Invite.INVITE_RESULT.FAILED.getCode());
                ErrorTestee errorTestee = new ErrorTestee();
                errorTestee.setTesteeId(testeeId);
                errorTestee.setActivityId(activity.getId());
                errorTestee.setInviteId(invite.getId());
                errorTestee.setInviteDate(new Date());
                JpaUtil.save(errorTestee);
            }
            else{
                invite.setInviteResult(Invite.INVITE_RESULT.SUCCESS.getCode());
                TesteeInviteResult successResult = testeeResult.testee_invite_result_list.get(0);
                invite.setSn(successResult.sn);
                invite.setLoginUrl(successResult.login_url);
                invite.setTestUrl(successResult.test_url);
            }
        }
        JpaUtil.update(invite);

        if(StringUtils.isBlank(activity.getPaperId())){
            return TesteeRegisterResultVO.redirectBeisenUrl(invite.getTestUrl());
        }
        else{
            PaperVO paper = getPaper(activity.getPaperId());
            if(paper==null){
                return TesteeRegisterResultVO.redirectBeisenUrl(invite.getTestUrl());
            }
            else{
                return TesteeRegisterResultVO.redirectLocalPaper(paper,invite.getId(),invite.getTestUrl());
            }
        }


    }

    @Override
    public List<ActivityInfo> getAllActivityFromBeisen(){
        List<ActivityInfo> activityInfoList = new ArrayList<>();
        int pageSize = 100;
        int pageIndex = 1;
        int totalCount = 0;
        do{
            ActivityInfoList activityInfos = interfService.getActivityList(pageSize,pageIndex);
            activityInfoList.addAll(activityInfos.activity_list);
            totalCount = activityInfos.total_count;
            pageIndex++;
        }
        while(pageIndex<=(totalCount/pageSize)+1);
        return activityInfoList;
    }


    /**
     * 同步北森活动状态
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public RunResultDTO syncActivity(){
        logger.info(">>>>>>>>>>>>>>>>syncActivity");
        List<ActivityInfo> activityInfoList =getAllActivityFromBeisen();
        logger.info(">>>>>>>>>>>>>>>>activity count:{}",CollectionUtils.isEmpty(activityInfoList)?0:activityInfoList.size());
        if(CollectionUtils.isEmpty(activityInfoList)){
            return RunResultDTO.empty();
        }

        for(ActivityInfo activityInfo:activityInfoList){
            List<Activity> activityList = activityService.getByBeisenActivityId(String.valueOf(activityInfo.id));
            if(CollectionUtils.isEmpty(activityList)){
                continue;
            }
            for(Activity activity:activityList){
                activity.setName(activityInfo.name);
                activity.setDescription(activityInfo.description);
                activity.setState(String.valueOf(activityInfo.state));
                activityService.update(activity);
            }
        }
        return RunResultDTO.success();
    }

    /**
     * 同步答题状态及答题结果
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public RunResultDTO syncTesteeStateAndResult(){
        logger.info(">>>>>>>>>>>>>>>>syncTesteeStateAndResult");
        try{
            Date now = new Date();
            Date yesterday = DateUtils.addDays(now,-1);
            //开始时间至结束时间+1天之间的邀请
            List<Invite> inviteList = JpaUtil.linq(Invite.class).equal("inviteResult",Invite.INVITE_RESULT.SUCCESS.getCode()).in("state",Invite.STATE.NOT_STARTED.getCode(),Invite.STATE.ASSESSMENT_PROCESSING.getCode()).lessThan("startTime",now).greaterThan("endTime",yesterday).list();
            if(CollectionUtils.isEmpty(inviteList)){
                return RunResultDTO.empty();
            }
            List<Invite> complatedList = syncTesteeState(inviteList);
            syncTesteeResult(complatedList);
        }
        catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>>syncTesteeStateAndResult error",e);
            return RunResultDTO.failed(StringUtils.substring(e.getMessage(),0,200));
        }

        return RunResultDTO.success();
    }

    @Override
    @Transactional(readOnly = false)
    public RunResultDTO syncTesteeUnSyncResult(){
        logger.info(">>>>>>>>>>>>>>>>syncTesteeUnSyncResult");
        Date now = new Date();
        Date yesterday = DateUtils.addDays(now,-1);
        //开始时间至结束时间+1天之间已完成答题的邀请
        List<Invite> complatedList = JpaUtil.linq(Invite.class).equal("state",Invite.STATE.ASSESSMENT_COMPLATED.getCode()).equal("resultState",Invite.RESULT_STATE.NOT_SYNC.getCode()).lessThan("startTime",now).greaterThan("endTime",yesterday).list();
        if(CollectionUtils.isEmpty(complatedList)){
            return RunResultDTO.empty();
        }
        syncTesteeResult(complatedList);
        return RunResultDTO.success();
    }

    @Override
    @Transactional(readOnly = false)
    public RunResultDTO syncTemplate(){
        logger.info(">>>>>>>>>>>>>>>>syncTemplate");
        List<Template> entities = JpaUtil.linq(Template.class).list();
        JpaUtil.remove(entities);
        try{
            TemplateList templateList = interfService.getEmailTemplateList();
            for(com.beisen.sdk.assessment.model.Template beisenTemplate:templateList){
                Template template = new Template();
                template.setId(beisenTemplate.id);
                template.setName(beisenTemplate.name);
                template.setTemplateType(String.valueOf(beisenTemplate.template_type));
                template.setSubject(beisenTemplate.Subject);
                template.setChannel("0");
                try{
                    Date date = DateUtils.parseDate(beisenTemplate.CreateTime,"yyyy-MM-dd'T'HH:mm:ss.SSS");
                    template.setTemplateCreateTime(date);
                }
                catch (Exception e){
                    logger.error("日期转换错误,{}",beisenTemplate.CreateTime,e);
                }
                JpaUtil.save(template);
            }
            return RunResultDTO.success();
        }
        catch (Exception e){
            logger.error(">>>>>>>>>>>>>>>>syncTemplate error",e);
            return RunResultDTO.failed(StringUtils.substring(e.getMessage(),0,200));
        }

    }

    /**
     * 同步答题状态，返回答题已完成的邀请列表
     * @param inviteList
     * @return
     */
    private List<Invite> syncTesteeState(List<Invite> inviteList){
        List<Invite> complatedList = new ArrayList<>();
        Map<String,Activity> activityMap = new HashMap<>();
        for(Invite invite:inviteList){
            String activityId = invite.getActivityId();
            Activity activity = null;
            if(activityMap.containsKey(activityId)){
                activity = activityMap.get(activityId);
            }
            else{
                activity = activityService.getById(Activity.class,activityId);
                activityMap.put(activityId,activity);
            }

            ActivityTesteeState state = interfService.getActivityTesteeState(Integer.parseInt(activity.getBsActivityId()),invite.getEmail());
            if(state!=null&&CollectionUtils.isNotEmpty(state.testee_list)){
                for(TesteeSN testeeSN:state.testee_list){
                    if(testeeSN!=null&&CollectionUtils.isNotEmpty(testeeSN.sn_list)){
                        for(SerialNumber serialNumber:testeeSN.sn_list){
                            if(StringUtils.equals(serialNumber.sn,invite.getSn())){
                                invite.setState(serialNumber.state);
                                JpaUtil.persist(invite);
                                if(StringUtils.equals(serialNumber.state,Invite.STATE.ASSESSMENT_COMPLATED.getCode())){
                                    complatedList.add(invite);
                                }
                            }
                        }
                    }
                }
            }
        }
        return complatedList;
    }

    /**
     * 同步已完成答题的结果
     * @param complatedList
     */
    private void syncTesteeResult(List<Invite> complatedList){
        if(CollectionUtils.isEmpty(complatedList)){
            return;
        }

        Map<String,Invite> snMap = new HashMap<>();
        Map<String,List<EmailSNParameter>> paramMap = new HashMap<>();
        Map<String,Activity> activityMap = new HashMap<>();
        for(Invite invite:complatedList){
            String activityId = invite.getActivityId();
            Activity activity = null;
            if(activityMap.containsKey(activityId)){
                activity = activityMap.get(activityId);
            }
            else{
                activity = activityService.getById(Activity.class,activityId);
                activityMap.put(activityId,activity);
            }

            if(!paramMap.containsKey(activity.getBsActivityId())){
                paramMap.put(activity.getBsActivityId(),new ArrayList<>());
            }
            EmailSNParameter emailSNParameter = new EmailSNParameter();
            emailSNParameter.sn = invite.getSn();
            emailSNParameter.email = invite.getEmail();
            paramMap.get(activity.getBsActivityId()).add(emailSNParameter);
            snMap.put(invite.getSn(),invite);
        }

        for(Map.Entry<String,List<EmailSNParameter>> entry:paramMap.entrySet()){
            ActivityTesteeResultList activityTesteeResultList = interfService.getTesteeResultByEmailAndSN(Integer.parseInt(entry.getKey()),entry.getValue());
            if(CollectionUtils.isEmpty(activityTesteeResultList)){
                continue;
            }
            for(ActivityTesteeResult activityTesteeResult:activityTesteeResultList){
                if(CollectionUtils.isEmpty(activityTesteeResult.testee_list)){
                    continue;
                }
                for(TesteeSNTest testeeSNTest:activityTesteeResult.testee_list){
                    if(CollectionUtils.isEmpty(testeeSNTest.sn_list)){
                        continue;
                    }
                    for(SNTest snTest:testeeSNTest.sn_list){
                        Invite invite = snMap.get(snTest.sn);
                        invite.setResultState(Invite.RESULT_STATE.SYNCED.getCode());
                        JpaUtil.update(invite);

                        com.hnichr.ump.common.assessment.entity.TesteeResult testeeResult = new com.hnichr.ump.common.assessment.entity.TesteeResult();
                        testeeResult.setInviteId(invite.getId());
                        testeeResult.setTenantId(invite.getTenantId());
                        if(snTest.summaryreport!=null){
                            testeeResult.setSummaryReportName(snTest.summaryreport.name);
                            testeeResult.setSummaryReportUrl(snTest.summaryreport.url);
                        }
                        JpaUtil.save(testeeResult);

                        if(CollectionUtils.isNotEmpty(snTest.composite_report_list)){
                            for(Report report:snTest.composite_report_list){
                                CompositeReport compositeReport = new CompositeReport();
                                compositeReport.setTesteeResultId(testeeResult.getId());
                                compositeReport.setTenantId(invite.getTenantId());
                                compositeReport.setReportNo(report.report_no);
                                compositeReport.setName(report.name);
                                compositeReport.setType(report.type);
                                compositeReport.setUrl(report.url);
                                compositeReport.setInviteId(invite.getId());
                                compositeReport.setLocalUrl(saveReportLocal(report.report_no,report.name,snTest.sn));
                                JpaUtil.save(compositeReport);
                            }
                        }

                        if(CollectionUtils.isNotEmpty(snTest.test_report_list)){
                            for(TestReport testReport:snTest.test_report_list){
                                TestResult testResult = new TestResult();
                                testResult.setTesteeResultId(testeeResult.getId());
                                testResult.setTenantId(invite.getTenantId());

                                try{
                                    Date testCreateTime = DateUtils.parseDate(testReport.create_time,"yyyy-MM-dd'T'HH:mm:ss.SSS");
                                    testResult.setTestCreateTime(testCreateTime);
                                }
                                catch (Exception e){
                                    logger.error("日期转换错误,{}",testReport.create_time,e);
                                }
                                if(testReport.test!=null){
                                    testResult.setName(testReport.test.name);
                                    testResult.setCent(testReport.test.cent);
                                    testResult.setSubCent(testReport.test.subcent);
                                    testResult.setType(testReport.test.type);
                                    testResult.setAnswerEffective(testReport.test.answer_effective);
                                    testResult.setExamineStatus(testReport.test.examineStatus);
                                    testResult.setCanMaunal(testReport.test.isCanMaunal);
                                    testResult.setExamSubjectivePartCent(testReport.test.examsubjectivepartcent);
                                    testResult.setExamObjectivePartCent(testReport.test.examobjectivepartcent);
                                }
                                JpaUtil.save(testResult);

                                if(testReport.test!=null&&CollectionUtils.isNotEmpty(testReport.test.dimension_list)){
                                    for(Dimension dimension:testReport.test.dimension_list){
                                        com.hnichr.ump.common.assessment.entity.Dimension dm = new com.hnichr.ump.common.assessment.entity.Dimension();
                                        dm.setTestResultId(testResult.getId());
                                        dm.setTenantId(invite.getTenantId());
                                        dm.setName(dimension.name);
                                        dm.setCent(dimension.cent);
                                        dm.setType(dimension.type);
                                        dm.setTotalCent(dimension.totalcent);
                                        JpaUtil.save(dm);
                                    }
                                }
                                if(CollectionUtils.isNotEmpty(testReport.report_list)){
                                    for(Report report:testReport.report_list){
                                        com.hnichr.ump.common.assessment.entity.TestReport rp = new com.hnichr.ump.common.assessment.entity.TestReport();
                                        rp.setTestResultId(testResult.getId());
                                        rp.setTenantId(invite.getTenantId());
                                        rp.setReportNo(report.report_no);
                                        rp.setName(report.name);
                                        rp.setType(report.type);
                                        rp.setUrl(report.url);
                                        rp.setInviteId(invite.getId());
                                        rp.setLocalUrl(saveReportLocal(report.report_no,report.name,snTest.sn));
                                        JpaUtil.save(rp);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private String saveReportLocal(String reportNo,String reportName,String sn){
        InputStream is = null;
        HttpURLConnection conn = null;
        try{
            String reportUrl = interfService.getReportDownloadUrl(reportNo);
            URL url = new URL(reportUrl);
            conn = (HttpURLConnection)url.openConnection();
            while(conn.getResponseCode()==302){
                String location = conn.getHeaderField("Location");
                conn.disconnect();
                url = new URL(location);
                conn = (HttpURLConnection)url.openConnection();
            }
            is = conn.getInputStream();
            String fileName = reportName+".pdf";
            String objectName = "assessment/"+DateUtil.format(DateTime.now(), "yyyy/MM/dd") + "/" + sn+"/"+fileName;
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(bucket).object(objectName)
                    .stream(is, conn.getContentLength(), -1).contentType("application/pdf").build();
            // 文件名称相同会覆盖
            ObjectWriteResponse response = minioClient.putObject(objectArgs);
            String returnUrl = resUrl+"/"+bucket+"/"+objectName;
            logger.info(">>>>>>>>>>>>>>returnUrl:{}",returnUrl);
            return returnUrl;
        } catch (Exception e) {
            logger.error("文件下载并且保存到minio失败：", e);
        }
        finally{
            if(is!=null){
                try{
                    is.close();
                }
                catch (IOException ignore){

                }
            }
            if(conn!=null){
                conn.disconnect();
            }
        }
        return null;
    }



    private List<ActivityVO>  assembleActivityVO(List<Activity> activityList ){
        List<ActivityVO> voList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(activityList)){
            for(Activity activity:activityList){
                ActivityVO vo = new ActivityVO();
                vo.setActivityId(activity.getId());
                vo.setActivityName(StringUtils.isNotBlank(activity.getDisplayName())?activity.getDisplayName():activity.getName());
                vo.setActivityDesc(activity.getDescription());
                voList.add(vo);
            }
        }
        return voList;
    }

    private TesteeRegisterResultVO registerInputValid(TesteeRegisterVO vo){
        //数据合法性校验
        if(StringUtils.isBlank(vo.getActivityId())){
            return TesteeRegisterResultVO.error("测评活动信息为空");
        }
        if(StringUtils.isBlank(vo.getEmail())){
            return TesteeRegisterResultVO.error("电子邮件地址为空");
        }
        if(!Validator.isEmail(vo.getEmail())){
            logger.error("电子邮件地址不合法:{}",vo.getEmail());
            return TesteeRegisterResultVO.error("电子邮件地址不合法");
        }

        if(StringUtils.isBlank(vo.getMobile())){
            return TesteeRegisterResultVO.error("手机号为空");
        }
        if(!Validator.isMobile(vo.getMobile())){
            logger.error("手机号不合法:{}",vo.getMobile());
            return TesteeRegisterResultVO.error("手机号不合法");
        }
        return null;
    }



    private PaperVO getPaper(String paperId){
        Paper paper = paperService.getById(Paper.class,paperId);
        if(paper == null||StringUtils.equals(paper.getDelFlag(),"1")){
            return null;
        }
        PaperVO paperVO = new PaperVO();
        paperVO.setPaperId(paperId);
        paperVO.setPaperName(paper.getPaperName());
        paperVO.setQuestionList(new ArrayList<>());
        List<Question> questionList = JpaUtil.linq(Question.class).equal("paperId",paperId).equal("delFlag","0").asc("orderNum","createTime").list();
        for(Question question:questionList){
            QuestionVO questionVO = new QuestionVO();
            questionVO.setQuestionId(question.getId());
            questionVO.setQuestionName(question.getQuestionName());
            questionVO.setQuestionType(question.getQuestionType());
            questionVO.setOptionList(new ArrayList<>());
            paperVO.getQuestionList().add(questionVO);
            List<Option> optionList = JpaUtil.linq(Option.class).equal("questionId",question.getId()).equal("delFlag","0").asc("orderNum","createTime").list();
            for(Option option:optionList){
                OptionVO optionVO = new OptionVO();
                optionVO.setOptionId(option.getId());
                optionVO.setOptionCode(option.getOptionCode());
                optionVO.setOptionName(option.getOptionName());
                questionVO.getOptionList().add(optionVO);
            }
        }
        return paperVO;
    }


}
